package logic

import (
	"context"
	"errors"
	"video/model/cache"
	"video/model/mysql"
	"video/pkg"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User
	err := findUser.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("该手机号未注册，请前往注册")
	}
	if findUser.Status == 1 {
		return nil, errors.New("账号已禁用，请联系管理员")
	}
	// 1 手机号 + 验证码     2 手机号 + 密码
	if in.LoginType == 1 {

		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if result == "" {
			return nil, errors.New("当前未发送短信验证码")
		}
		if result != in.SendSms {
			return nil, errors.New("当前短信验证码错误，请重新输入")
		}

	} else if in.LoginType == 2 {

		if pkg.Md5Str(in.Password) != findUser.Password {
			return nil, errors.New("密码错误，请重新输入")
		}

	} else {
		return nil, errors.New("请选择正确的登录方式")
	}

	return &videorpc.LoginResponse{
		UserId: int64(findUser.ID),
	}, nil
}
